<template>
  <div class="challengeBox-container">
    <!--    <van-button type="primary" @click="addChallenge">添加擂台</van-button>-->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="(page - 1) * 10 >= total"
        finished-text="没有更多了"
        @load="onLoadMore"
      >
        <ChallengeItem @changeStatus="changeStatus" @controll="onShowControl(item.id)" :challenge="item"
                       v-for="item in challengeList"
                       :key="item.id"></ChallengeItem>
      </van-list>
      <van-back-top bottom="10vh" />
    </van-pull-refresh>

    <van-action-sheet
      v-model:show="showControl"
      :actions="actions"
      cancel-text="关闭"
      close-on-click-action
      @select="onSelect"
    />

    <VanDialog
      show-cancel-button @cancel="showDialog = undefined" :show="showDialog === 1" title="赏品"
      cancel-button-text="关闭" :show-confirm-button="false">
      <van-list style="max-height: 70vh; overflow-y: scroll;" v-model:loading="prizeLoading"
                @load="onPrizeLoadMore" finished-text="没有更多了" :finished="(dialogPage * 10 >= dialogTotal)">
        <div class="prize-item" v-for="item in prizeList" :key="item.id">
          <ChallengePrize :prize="item" />
          <div class="prize-info">
            {{ item.level_name }} ￥{{ item.recovery_price }}
            <van-button size="mini" @click="deleteChallengePrize(item.id)">删除</van-button>
          </div>
        </div>
      </van-list>
    </VanDialog>

    <VanDialog :show-confirm-button="false" show-cancel-button @cancel="showDialog = undefined" :show="showDialog === 2"
               title="记录"
               cancel-button-text="关闭">
      <van-list style="max-height: 70vh; overflow-y: scroll;" v-model:loading="prizeLoading"
                @load="onRecordLoadMore" finished-text="没有更多了" :finished="(dialogPage * 10 >= dialogTotal)">
        <div class="prize-item" v-for="item in prizeList" :key="item.id">
          <UserInfo :id="item.user_id" :avatar="item.avatar" :nickname="item.nickname" />
          <div class="prize-info">
            X{{ item.num }} {{ item.level_name }} ￥{{ item.recovery_price }}
            <div>{{ item.created_at }}</div>
          </div>
        </div>
      </van-list>
    </VanDialog>
    <VanDialog title="续箱" show-cancel-button show-confirm-button
    @cancel="showDialog = undefined" :show="showDialog === 3" @confirm="renewBoxs">
      <van-field v-model="boxNum" placeholder="请输入箱数" />
    </VanDialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  reqChangeChallengeStatus,
  reqGetChallengeList,
  reqGetChallengePrizes,
  reqGetChallengeRecord,
  reqChallengeRenewBoxs, reqDeleteChallengePrize
} from '@/api/challenge'
import ChallengeItem from '@/components/ChallengeItem.vue'
import ChallengePrize from '@/components/ChallengePrize.vue'
import UserInfo from '@/components/UserInfo.vue'
import { showLoadingToast, showToast } from 'vant'

const challengeList = ref([])
const loading = ref(false)
const page = ref(1)
const total = ref(0)
const refreshing = ref(false)
const showControl = ref(false)
const showDialog = ref(undefined)
const prizeList = ref([])
const currentId = ref(0)
const dialogPage = ref(1)
const dialogTotal = ref(0)
const prizeLoading = ref(false)
const boxNum = ref(1)

const actions = [
  { id: 1, name: '赏品' },
  { id: 2, name: '记录' },
  { id: 3, name: '续箱' }
]

const onSelect = (e) => {
  prizeLoading.value = true
  showDialog.value = e.id
  dialogPage.value = 1
  dialogTotal.value = 0
  switch (e.id) {
    case 1:
      getChallengePrizes()
      break
    case 2:
      getChallengeRecord()
      break
    case 3:
      break
  }
}

const changeStatus = async ({ id, status }) => {
  try {
    const result = await reqChangeChallengeStatus(id, { status: status ? 0 : 1 })
    if (result.code === 200) {
      onRefresh()
    } else {
      throw new Error(result.msg)
    }
  } catch (e) {
    console.log(e)
  }
}

const onShowControl = (id) => {
  currentId.value = id
  showControl.value = true
}

onMounted(() => {
  refreshing.value = true
  getChallengeList()
})

const onRefresh = () => {
  page.value = 1
  total.value = 0
  getChallengeList()
}

const onLoadMore = () => {
  getChallengeList()
}

const onPrizeLoadMore = () => {
  getChallengePrizes()
}

const onRecordLoadMore = () => {
  getChallengeRecord()
}

const getChallengeList = async () => {
  try {
    const result = await reqGetChallengeList({ page: page.value })
    if (result.code === 200) {
      if (page.value === 1) {
        challengeList.value = result.data.data
      } else {
        challengeList.value.push(...result.data.data)
      }
      total.value = result.data.total
      page.value++
    }
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

const getChallengePrizes = async () => {
  try {
    const result = await reqGetChallengePrizes({
      challengeBoxId: currentId.value,
      page: dialogPage.value
    })
    if (result.code === 200) {
      if (dialogPage.value === 1) {
        prizeList.value = result.data.data
      } else {
        prizeList.value.push(...result.data.data)
      }
      dialogPage.value++
      dialogTotal.value = result.data.total
    }
  } catch (e) {
    console.log(e)
  } finally {
    prizeLoading.value = false
  }
}

const getChallengeRecord = async () => {
  try {
    const result = await reqGetChallengeRecord({
      blind_box_id: currentId.value,
      page: dialogPage.value
    })
    if (result.code === 200) {
      if (dialogPage.value === 1) {
        prizeList.value = result.data.data
      } else {
        prizeList.value.push(...result.data.data)
      }
      dialogPage.value++
      dialogTotal.value = result.data.total
    }
  } catch (e) {
    console.log(e)
  } finally {
    prizeLoading.value = false
  }
}

const renewBoxs = async () => {
  const loadingToast = showLoadingToast({type: 'loading', message: '续箱中'})
  try {
    const result = await reqChallengeRenewBoxs({
      id: currentId.value,
      num: boxNum.value
    })
    if (result.code === 200) {
      showToast({type: 'success', message: '续箱成功', duration: 3000})
      showDialog.value = undefined
    } else {
      showToast({type: 'fail', message: '续箱失败', duration: 3000})
    }
  } catch (e) {
    console.log(e)
  } finally {
    loadingToast.close()
  }
}

const deleteChallengePrize = async (id) => {
  try {
    const result = await reqDeleteChallengePrize(id)
    if (result.code === 200) {
      dialogPage.value = 1
      dialogTotal.value = 0
      await getChallengePrizes()
      showToast({type: 'success', message: '删除成功'})
    } else {
      showToast({type: 'fail', message: '删除失败'})
    }
  } catch (e) {
    console.log(e)
  }
}
</script>

<style lang="less" scoped>
.challengeBox-container {
  height: 100%;

  .prize-item {
    padding: 10px;
    display: flex;

    .prize-info {
      font-size: 12px;
    }
  }
}
</style>
